package com.url;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class UrlExample {
    @Test
    public void test1() throws MalformedURLException {
        URL url = new URL("https://www.google.com");
        // 获取协议
        System.out.println("协议: " + url.getProtocol());
        // 获取主机名
        System.out.println("主机名: " + url.getHost());
        // 获取端口号
        System.out.println("端口号: " + url.getPort()); // 如果没有指定端口，则返回 -1
        // / or specific path
        System.out.println("Path: " + url.getPath());
        // path + query
        System.out.println("File: " + url.getFile());
        // parameters after ?
        System.out.println("Query: " + url.getQuery());
    }

    /**
     * 读取网页内容
     */
    @Test
    public void test2() throws IOException {
        try {
            URL myUrl = new URL("https://www.example.com");
            HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
            conn.setRequestMethod("GET"); // 默认为GET，可以不显式设置

            System.out.println("Response Code: " + conn.getResponseCode());
            System.out.println("Response Message: " + conn.getResponseMessage());

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 检查是否成功
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                    content.append(System.lineSeparator());
                }
                in.close();
                System.out.println("Content:\n" + content.toString().substring(0, 200) + "..."); // 打印前200个字符
            } else {
                System.out.println("GET request not worked");
            }
            conn.disconnect(); // 断开连接
        } catch (MalformedURLException e) {
            System.err.println("URL格式错误: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO异常: " + e.getMessage());
        }

    }
}
